{% extends 'baykeshop/base_site.html' %}

{% load i18n static %}

{% block title %}购物车{% endblock %}

{% block extrahead_script %}
<script src="{% static 'baykeshop/js/axios.min.js' %}"></script>
<script src="{% static 'baykeshop/js/request.js' %}"></script>
{% endblock %}

{% block extrastyle %}
<style>
    .table td {
        vertical-align: middle;
    }
</style>
{% endblock %}

{% block breadcrumb %}
<div class="container">
    <nav class="breadcrumb is-marginless mt-3 mb-3 is-small" aria-label="breadcrumbs">
      <ul>
        <li><a href="{% url 'baykeshop:home' %}">首页</a></li>
        <li class="is-active"><a href="#" aria-current="page">购物车</a></li>
      </ul>
    </nav>
</div>
{% endblock %}

{% block container %}
    {{ datas|json_script:"carts-data" }}
    <div class="container mt-3" id="carts">
        <div class="box is-radiusless" v-if="cartsData.length > 0">
            <template>
                <b-table
                    checkable
                    hoverable
                    :is-row-checkable="(row) => Number(row.sku.stock) > Number(row.num)"
                    :checked-rows.sync="checkedRows" 
                    :data="cartsData">
                    <b-table-column field="id" label="ID" v-slot="props">
                        {$ props.row.id $}
                    </b-table-column>
                    <b-table-column field="pic" label="商品图" v-slot="props">
                        <figure class="image is-128x128">
                            <b-image
                                :src="`${props.row.sku.goods.pic}`"
                                :alt="props.row.sku.goods.title"
                                ratio="1by1"
                            ></b-image>
                        </figure>
                    </b-table-column>
                    <b-table-column field="title" label="标题" v-slot="props">
                        {$ props.row.sku.goods.title $}
                        <div class="is-flex">
                            <p class="mt-2 mr-3" v-for="spec, i in props.row.sku.options" :key="i">
                                <span class=" has-text-grey-light">
                                    {$ spec.spec $}
                                </span>：<strong>{$ spec.name $}</strong> 
                            </p>
                        </div>
                    </b-table-column>
                    <b-table-column field="stock" label="库存" width="120" v-slot="props">
                        {$ props.row.sku.stock $}
                    </b-table-column>
                    <b-table-column field="price" label="单价" width="120" v-slot="props">
                        <span class="is-size-5 has-text-grey">¥</span>{$ props.row.sku.price $}
                    </b-table-column>
                    <b-table-column field="num" label="数量" v-slot="props">
                        <b-field>
                            <b-numberinput
                                @input="updateCartNum(props.row)"
                                controls-position="compact"
                                size="is-small"
                                type="is-light"
                                :min="1"
                                :max="props.row.sku.stock"
                                :editable='true'
                                v-model="props.row.num">
                            </b-numberinput>
                        </b-field>
                    </b-table-column>
                    <b-table-column field="total_price" label="小计" width="120" v-slot="props">
                        <span class="is-size-5 has-text-grey">¥</span>{$ parseFloat(props.row.sku.price * props.row.num).toFixed(2) $}
                    </b-table-column>
                    <b-table-column field="caozuo" label="操作" width="80" v-slot="props">
                        <button class="delete" @click="delCart(props.row)">删除</button>
                    </b-table-column>

                    <template #footer>
                        <div class="has-background-light is-flex is-align-items-center is-justify-content-space-between">
                            <div class="has-text-danger-dark ml-3">
                                已选<span class="is-size-4 pl-2 pr-2">{$ checkedRows.length $}</span>件商品 
                            </div>
                            <div class=" is-flex is-align-items-center has-text-danger-dark ">
                                <span class="is-size-5">合计：</span> <span class="is-size-3 pr-5">¥ {$ totalPrice $}</span>
                                <button 
                                    class="button is-primary is-radiusless is-large pl-6 pr-6" 
                                    :disabled="checkedRows.length > 0 ? false : true"
                                    @click="cartBuy">
                                    去结算
                                </button>
                            </div>
                        </div>
                    </template>
                </b-table>
            </template>
        </div>
        <div class="has-text-centered has-text-danger is-size-5" v-else> 
            <img src="{% static 'baykeshop/img/noCart1.png' %}">
            <p> 亲，购物车还是空的哟~ </p>
            <a class=" button is-primary is-outlined mt-4" href="{% url 'baykeshop:home' %}">继 续 逛</a>
        </div>
    </div>
{% endblock %}


{% block vue %}
    <script>
        var cartsData = JSON.parse(document.getElementById('carts-data').textContent);
        var carts = new Vue({
            el: '#carts',
            delimiters: ['{$', '$}'],
            data: {
                cartsData,
                checkedRows: [],  // 选择的动态
                totalPrice: 0
            },
            created(){
                cartsData.forEach(item => {
                    if (item.num < item.sku.stock){
                        this.checkedRows.push(item)
                    }
                })
            },
            watch:{
                checkedRows: {
                    handler: function(val, oldval){
                        let totalPrice = 0;
                        val.forEach(element => {
                           totalPrice += element.num * element.sku.price
                           this.totalPrice = parseFloat(totalPrice).toFixed(2)
                        });
                    },
                    deep: true
                }
            },
            methods: {
                updateCartNum(row){
                    request({
                        url: `/cart/${row.id}/`,
                        method: 'patch',
                        data:{
                            num: row.num
                        }
                    }).then(res => {
                        if (res.status == 200){
                            navbar.toastMessage('is-success', '数量修改成功！')
                        }else{
                            navbar.toastMessage('is-danger', '修改失败，请刷新重试！')
                        }
                    })
                },

                delCart(row){
                    this.$buefy.dialog.confirm({
                        message: '是否确认删除该购物车商品！',
                        cancelText: '取消',
                        onConfirm: () => {
                            request({
                                url: `/cart/${row.id}/`,
                                method: 'delete',
                            }).then(res => {
                                if (res.status == 204){
                                    // 前端删除数组
                                    this.cartsData.forEach(item => {
                                        if (item.id == row.id){
                                            this.cartsData.splice(this.cartsData.indexOf(item), 1)
                                            this.checkedRows.splice(this.checkedRows.indexOf(item), 1)
                                            cartNum._data.cartcount = parseInt(cartNum._data.cartcount) - parseInt(row.num)
                                        }
                                    })
                                    navbar.toastMessage('is-success', '删除成功！')
                                }
                            })
                        }
                    })
                },

                cartBuy(){
                    request({
                        url: `{% url 'baykeshop:cache' %}`,
                        method: 'post',
                        data: {
                            skus: this.checkedRows, 
                            action: 'cartBuy'
                        }
                    }).then(res => {
                        console.log(this.checkedRows)
                        if (res.status == 201){
                            location.href = `{% url 'baykeshop:confirm' %}?action=cartBuy`
                            navbar.toastMessage('is-success', res.data.message)
                        }else{
                            navbar.toastMessage('is-danger', res.data.message)
                        }
                        
                    })
                }
            },
        })
    </script>
{% endblock %}
    
    